package com.jingdong.controller;
import com.jingdong.filter.Constant;
import com.jingdong.model.User;
import com.jingdong.service.user.UserService;
import com.jingdong.utils.CaptchaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.management.MonitorInfo;

@Controller
@RequestMapping("user")

public class UserController {
    @Autowired
    private UserService userService;
    private ProductTypeListController productTypeListController;
    @RequestMapping("toLogin")
    public ModelAndView toLogin(){
        ModelAndView mav=new ModelAndView("user/login");
        return mav;
    }
    //登陆验证码
    @RequestMapping(value = "/captcha", method = RequestMethod.GET)
    @ResponseBody
    public Object captcha(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        CaptchaUtil.outputCaptcha(request, response);
        return null;
    }
    @RequestMapping("login")
    public @ResponseBody Object login(String username, String  password, HttpSession httpSession,String validationCode){
        String randomString= httpSession.getAttribute("randomString").toString().toLowerCase();
        if (randomString.equals(validationCode)) {
            User user = userService.Login(username, password);
            httpSession.setAttribute("user", user);
            httpSession.setMaxInactiveInterval(3600);
            httpSession.setAttribute(Constant.SESSIONKEY,"user");
            return  user;
        }else {
            return null;
        }
    }
@RequestMapping("loginOut")
    public ModelAndView loginOut(HttpSession session){
        session.setAttribute("","");
        session.setAttribute(Constant.SESSIONKEY,"");
        return toLogin();
}
}
